package com.example.maryttsspringbootdemo.recorder;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.sound.sampled.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

@Component
public class AudioRecorder {
    // 确保AudioRecorder中的采样率与Vosk配置一致
    @Value("${mary.sample-rate}")
        private int sampleRate;
    private static final int SAMPLE_SIZE_IN_BITS = 16;
    private static final int CHANNELS = 1;
    private static final boolean SIGNED = true;
    private static final boolean BIG_ENDIAN = false;

    public void appendToWav(byte[] audioData, String filename) throws IOException, UnsupportedAudioFileException {
        AudioFormat format = new AudioFormat(sampleRate, SAMPLE_SIZE_IN_BITS, CHANNELS, SIGNED, BIG_ENDIAN);
        ByteArrayInputStream bais = new ByteArrayInputStream(audioData);
        AudioInputStream ais = new AudioInputStream(bais, format, audioData.length / 2);
    
        File file = new File(filename);
        if(file.exists()) {
            AudioInputStream existingAis = AudioSystem.getAudioInputStream(file);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] data = new byte[4096];
            int nRead;
            while ((nRead = existingAis.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            byte[] existingData = buffer.toByteArray();

            // 合并新旧数据
            byte[] combined = new byte[existingData.length + audioData.length];
            System.arraycopy(existingData, 0, combined, 0, existingData.length);
            System.arraycopy(audioData, 0, combined, existingData.length, audioData.length);

            // 重新生成完整的WAV文件
            bais = new ByteArrayInputStream(combined);
            ais = new AudioInputStream(bais, format, combined.length / 2);
        }
        AudioSystem.write(ais, AudioFileFormat.Type.WAVE, file);
    }

    public void writeToWav(byte[] audioData, String filename) throws IOException, UnsupportedAudioFileException {
        AudioFormat format = new AudioFormat(sampleRate, SAMPLE_SIZE_IN_BITS, CHANNELS, SIGNED, BIG_ENDIAN);
        ByteArrayInputStream bais = new ByteArrayInputStream(audioData);
        AudioInputStream ais = new AudioInputStream(bais, format, audioData.length / 2);

        File file = new File(filename);
        AudioSystem.write(ais, AudioFileFormat.Type.WAVE, file);
    }
}